<script lang="ts" setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import * as echarts from 'echarts/core';
  const props = defineProps({
    dataBar1: { type: Object as () => any, required: true },
    datax: { type: Object as () => any, required: true },
  });

  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;

  const option = ref<any>({
    tooltip: {
      trigger: 'axis', // 坐标轴触发 tooltip
      axisPointer: { type: 'cross' }, // 十字准星指示
      appendToBody: true, // 关键设置
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '0%',
      containLabel: true, // 让 grid 包含坐标轴文本
    },
    xAxis: {
      type: 'category',
      data: props.datax ?? [], // X 轴类目
      axisLabel: {
        show: true,
        color: '#fff',
      },
      axisTick: {
        show: false,
      },
    },
    yAxis: [
      {
        type: 'value',
        axisLabel: {
          formatter: '{value}',
          color: '#fff',
        },
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: false,
          lineStyle: {
            type: 'dashed',
            color: '#ccc',
          },
        },
      },
    ],
    series: [
      {
        type: 'bar',
        barWidth: 15,
        data: props.dataBar1 ?? [],
        yAxisIndex: 0,
        itemStyle: {
          color: {
            type: 'linearGradient',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(32, 242, 253, 1)', // 顶部颜色
              },
              {
                offset: 1,
                color: 'rgba(51, 226, 236, 0)', // 底部颜色
              },
            ],
          },
        },
        label: {
          show: true,
          position: 'top',
          color: '#fff',
          fontSize: 12,
          formatter: '{c}%',
        },
      },
    ],
  });

  const initCharts = () => {
    try {
      if (chartRef.value && !chartInstance) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance?.setOption(option.value, true);
      }
    } catch (error) {
      console.error('图表初始化失败:', error);
    }
  };

  const updateChart = () => {
    option.value.series[0].data = props.dataBar1 ?? [];
    option.value.xAxis.data = props.datax ?? [];
    chartInstance?.setOption(option.value, true);
    handleResize();
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      initCharts();
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', updateChart);
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', updateChart);
    chartInstance?.dispose();
  });

  watch(
    () => [props.datax, props.dataBar1],
    () => updateChart(),
    { deep: true }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
  });

  // 窗口大小变化处理
  const handleResize = () => {
    nextTick(() => {
      chartInstance?.resize();
    });
  };
</script>
<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
